package com.term.appadmin.controller;

import com.term.util.response.AjaxResponse;
import org.springframework.context.MessageSource;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;

import javax.annotation.Resource;

/**
 * Created by chenGang on 2017/1/19.
 */
public class BaseController {

    @Resource
    private MessageSource messageSource;


    private static final String defaultErrorMsg = "表单验证失败";
    /**
     * 设置html标题
     * @param model
     * @param title
     */
    protected void setPageTitle(Model model, String title) {
        model.addAttribute("pageTitle", title);
    }

    /**
     * 显示返回标签
     * @param model
     */
    protected void enableGoBack(Model model) {
        model.addAttribute("pageGoBack", true);
    }


    protected AjaxResponse defaultError(BindingResult result) {
        return defaultError(result, defaultErrorMsg);
    }

    protected AjaxResponse defaultError(BindingResult result, String errorMsg) {
        return AjaxResponse.validationFail(getMessageSource()).msg(errorMsg).reason(result.getAllErrors().get(0).getDefaultMessage());
    }


    public MessageSource getMessageSource() {
        return messageSource;
    }
}
